<?php

namespace app\home\controller;

use app\home\model\Idfa724Model;
use app\home\model\Order;
use app\home\service\NotifyService;
use app\home\service\OrderService;
use think\Db;
use think\helper\hash\Md5;
use think\Model;
use think\Request;
use think\response\Json;

class Pay800069 extends BasePay
{

    const  secretKey = '2Djqftmjbspnn5Wx';

    public static function email()
    {
        return [
            'benson@google.com',
            'dorisca@google.com',
            'stanmary@google.com',
            'ceciltom@google.com',
            'jennyaw@google.com',
            'louised@google.com',
        ];
    }
    public static function mobile()
    {
        return [
            7166643618,
            2642808917,
            8591023253,
            7016008244,
            3144989335,
            3306741675,
        ];
    }

    public static function firstName()
    {
        return [
            'Benson',
            'Jessica',
            'Stan',
            'Cecil',
            'Jenny',
            'Louis',
        ];
    }
    public static function lastName()
    {
        return [
            'Grey',
            'Doris',
            'Mary',
            'Tom',
            'Law',
            'Edison',
        ];
    }

    public function __construct()
    {
        header('Content-Type: text/html;charset=utf-8');
        header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
        header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
        header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin'); // 
    }

    public function order()
    {
        
        $number = mt_rand(0, 5);

        parent::order();
        $params = Request::instance()->param();

        $json_string = file_get_contents(env('PLATFORM.USD'));
        $config = json_decode($json_string, true);
        $usd  = $config[$this->order_array['goods_id']];
        if (empty($usd)) {
            mylog('计费点对应的美元金额找不到');
            throw new \Exception('计费点对应的美元金额找不到');
        }
        $coin = $usd['Mpay'];

        $payData = [
            'merchantNo' => 'M1831602417119203422',
            'appKey' => 'A1831628066470957094',
            "orderNo" => $this->order_array['id'],
            "amount" => $coin,
            'mobile' => self::mobile()[$number],
            'email' => self::email()[$number],
            'firstName' => self::firstName()[$number],
            'lastName' => self::lastName()[$number],
            'callbackUrl' => 'https://pay.carcadefishing.com/home/pay800069/notify',
        ];
        $sign = md5($this->signData($payData) . self::secretKey);
        $payData['sign'] = $sign;
        // $url = 'https://api-uat.v5pay.com/cgi/cashier/v2/payin';
        $url = 'https://api.v5pay.com/cgi/cashier/v2/payin';
        $response = $this->curl($url, json_encode($payData));
        if (empty(json_decode($response, true))) {
            mylog('下单失败');
            exit(json_encode(['code' => 0, 'msg' => '', 'data' => []]));
        }
        $data = json_decode($response, true);
        if ($data['code'] != '1000') {
            mylog('下单失败');
            exit(json_encode(['code' => 0, 'msg' => '', 'data' => []]));
        }

        (new \app\home\model\TradeLog)->where('id', $this->order_array['id'])->update(['dollPrice' => $coin, 'dollPriceType' => 'usd']);

        exit(json_encode(['code' => 1, 'msg' => '', 'data' => $data]));
    }




    public function notify()
    {
        parent::notify();
        $params = $this->params;
        mylog($params);
        try {
            //验证签名
            $sign = md5($this->signData($params) . self::secretKey);

            if ($sign != strtolower($params['sign'])) {
                throw new \Exception('sign false');
            }

            if ($params['status'] != 2) {
                throw new \Exception('status false');
            }
            //保存第三方单号
            $tradeLog = (new \app\home\model\TradeLog)->where(['id' => $params['orderNo']])->find();
            if ($tradeLog['dollPrice'] != $params['amount']) {
                throw new \Exception('订单金额不一致' . ' 传参:' .  $params['amount'] . ' 实际:' . $tradeLog['dollPrice']);
            }

            if ($tradeLog["status"] == OrderService::PAY_STATUS_PAID) {
                mylog("800069 订单已经处理过了 订单id" . $tradeLog['id']);
                exit('success');
            }

            //发货
            $notifyService = new NotifyService();
            if ($notifyService->notifyProcess($tradeLog) == false) {
                throw new \Exception('notifyProcess false');
            }
            //facebook广告回传
            if (in_array($tradeLog->channel_id, (new AdFacebook())->channel_id)) {
                $AdFacebook = new AdFacebook();
                $AdFacebook->pay($tradeLog->userid, $tradeLog->amount, $tradeLog->channel_id);
            }
            exit('success');
        } catch (\Exception $exception) {
            mylog('800069-error:' . $exception->getMessage() . ' line:' . $exception->getLine() . ' file:' . $exception->getFile());
            exit('FAIL');
        }
    }

    public function signData($data)
    {
        ksort($data);
        $tmp = [];
        foreach ($data as $k => $v) {
            if ($k == 'sign') {
                continue;
            }
            $tmp[] = $k . '=' . $v;
        }
        $str = implode('&', $tmp);
        return $str;
    }


    /**
     * @param $url
     * @param null $body
     * @return bool|string
     * @throws Exception
     */
    protected function curl($url, $body = null)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS,  $body);
        //TODO 证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $response = curl_exec($ch);

        curl_close($ch);
        mylog($response);
        return $response;
    }
}
